extends Node

# 最新
var peer = ENetMultiplayerPeer.new()

const URL = "http://localhost:8888/network/receive"

func _on_create_button_up() -> void:
	$HTTPRequest.request_completed.connect(_on_local_request_completed)
	
	peer.create_server(1234)
	multiplayer.multiplayer_peer = peer
	
	var body = JSON.stringify({
		"ip": "172.0.0.1",
		"port": 2222
	})
	var headers = ["Content-Type: application/json"]
	var error = $HTTPRequest.request(URL, headers, HTTPClient.METHOD_POST, body)
	if error != OK:
		push_error("请求发送失败" + str(error))
	
	#get_tree().change_scene_to_file("res://scene/main.tscn")

func _on_join_button_up() -> void:
	get_tree().change_scene_to_file("res://scene/information.tscn")

func _on_local_request_completed(result: int, _response_code: int, _headers: PackedStringArray, _body: PackedByteArray) -> void:
	print("----- 请求结果 -----")
	print("状态: ", _get_result_text(result))
	print("HTTP 状态码: ", _response_code)
	print("响应头: ", _headers)
	print("响应体 (原始): ", _body)
	
	# 解析 JSON 响应（如果是 JSON 格式）
	if _body.size() > 0:
		var json = JSON.new()
		var parse_result = json.parse(_body.get_string_from_utf8())
		if parse_result == OK:
			print("解析后的 JSON: ", json.get_data())
		else:
			print("JSON 解析失败: ", json.get_error_message())

# 将 result 枚举值转为可读文本
func _get_result_text(result: int) -> String:
	match result:
		HTTPRequest.RESULT_SUCCESS: return "成功"
		HTTPRequest.RESULT_CHUNKED_BODY_SIZE_MISMATCH: return "分片数据大小不匹配"
		HTTPRequest.RESULT_CANT_CONNECT: return "无法连接"
		HTTPRequest.RESULT_CANT_RESOLVE: return "域名解析失败"
		HTTPRequest.RESULT_CONNECTION_ERROR: return "连接错误"
		HTTPRequest.RESULT_TLS_HANDSHAKE_ERROR: return "SSL 握手失败"
		HTTPRequest.RESULT_NO_RESPONSE: return "无响应"
		HTTPRequest.RESULT_BODY_SIZE_LIMIT_EXCEEDED: return "响应体过大"
		_: return "未知状态 (" + str(result) + ")"
